package service

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"monitoring-api/models"
	"monitoring-api/serializer"
	"sort"
	"strconv"
	"strings"
)

type Condition struct {
	ResTime string `json:"res_time"` // 响应时间，查询时间范围内的数据，格式为两个数字，中间用_分割，单位毫秒
	SendURL string `json:"send_url"` // 请求路径， 查询请求路径中包含参数的数据
	Success string `json:"success"`  // 成功/失败请求，过滤成功/失败的请求，0表示成功，1表示失败，转化成字符串
	Time    string `json:"time"`     // 时间范围，查询起止时间内的数据，格式为两个时间戳，中间用_分割
	URL     string `json:"url"`      // 页面路径，查询路径中包含参数的数据
}

type GetReqLogsService struct {
	WebID     int64 `json:"web_id"`
	Page      int64 `json:"page"`
	Condition Condition
}

func (service *GetReqLogsService) Query() serializer.Response {
	logs := make([]models.Req, 0)
	err, success, startTime, endTime, resStartTime, resEndTime, url, sendUrl := service.handleCondition()
	//查询语句
	var filter bson.D
	if success != -1 {
		if success == 1 {
			filter = bson.D{{"webid", service.WebID},
				{"time", bson.D{{"$gt", startTime}}},
				{"time", bson.D{{"$lte", endTime}}},
				{"success", true},
				{"url", bson.D{{"$regex", url}}},
				{"sendurl", bson.D{{"$regex", sendUrl}}},
				{"restime", bson.D{{"$gt", resStartTime}}},
				{"restime", bson.D{{"$lte", resEndTime}}},
			}
		} else {
			filter = bson.D{{"webid", service.WebID},
				{"time", bson.D{{"$gt", startTime}}},
				{"time", bson.D{{"$lte", endTime}}},
				{"success", false},
				{"url", bson.D{{"$regex", url}}},
				{"sendurl", bson.D{{"$regex", sendUrl}}},
				{"restime", bson.D{{"$gt", resStartTime}}},
				{"restime", bson.D{{"$lte", resEndTime}}},
			}
		}
	} else {
		filter = bson.D{{"webid", service.WebID},
			{"time", bson.D{{"$gt", startTime}}},
			{"time", bson.D{{"$lte", endTime}}},
			{"url", bson.D{{"$regex", url}}},
			{"sendurl", bson.D{{"$regex", sendUrl}}},
			{"restime", bson.D{{"$gt", resStartTime}}},
			{"restime", bson.D{{"$lte", resEndTime}}},
		}
	}
	opts := options.Find().SetSkip((service.Page - 1) * 10).SetLimit(10)
	//获取文档总数
	total, err := models.Mongo.Collection("requests").CountDocuments(context.TODO(), filter)
	//分页查询
	cursor, err := models.Mongo.Collection("requests").Find(context.TODO(), filter, opts)
	if err != nil {
		return serializer.Response{
			Code:    500,
			Message: "数据库查询错误",
			Error:   err.Error(),
		}
	}
	// display the results
	var results []bson.M
	if err = cursor.All(context.TODO(), &results); err != nil {
		return serializer.Response{
			Code:    500,
			Message: "服务器错误",
			Error:   err.Error(),
		}
	}
	for _, result := range results {
		log := models.Req{}
		log.Kind = result["kind"].(int64)
		log.Time = result["time"].(int64)
		log.URL = result["url"].(string)
		log.WebID = result["webid"].(int64)
		log.Success = result["success"].(bool)
		log.ResBody = result["resbody"].(string)
		log.SendURL = result["sendurl"].(string)
		log.ResTime = result["restime"].(int64)
		log.Status = result["status"].(int64)
		log.Way = result["way"].(string)
		logs = append(logs, log)
	}
	//按时间降序排列
	sort.Slice(logs, func(x, y int) bool {
		return logs[x].Time > logs[y].Time
	})
	return serializer.BuildReqResponse(logs, int64(total), service.Page)
}

// 处理查询条件
func (service *GetReqLogsService) handleCondition() (error, int64, int64, int64, int64, int64, string, string) {
	//处理时间
	time := strings.Split(service.Condition.Time, "_")
	startTime, err := strconv.ParseInt(time[0], 10, 64)
	if err != nil {
		return err, 0, 0, 0, 0, 0, "", ""
	}
	endTime, err := strconv.ParseInt(time[1], 10, 64)
	if err != nil {
		return err, 0, 0, 0, 0, 0, "", ""
	}
	//处理响应时间范围
	var resStartTime, resEndTime int64
	if service.Condition.ResTime != "" {
		DTime := strings.Split(service.Condition.ResTime, "_")
		resStartTime, err = strconv.ParseInt(DTime[0], 10, 64)
		if err != nil {
			return err, 0, 0, 0, 0, 0, "", ""
		}
		resEndTime, err = strconv.ParseInt(DTime[1], 10, 64)
		if err != nil {
			return err, 0, 0, 0, 0, 0, "", ""
		}
	} else {
		resStartTime = 0
		resEndTime = 9999999
	}
	//处理success
	var success int64
	if service.Condition.Success != "" {
		if service.Condition.Success == "1" {
			success = 1
		} else {
			success = 0
		}
	} else {
		success = -1
	}
	//处理url
	var url string
	if service.Condition.URL != "" {
		url = service.Condition.URL
	} else {
		url = ""
	}
	//处理sendUrl
	var sendUrl string
	if service.Condition.URL != "" {
		url = service.Condition.URL
	} else {
		url = ""
	}
	return err, success, startTime, endTime, resStartTime, resEndTime, url, sendUrl
}
